/*
	THIS DO FILE PERFORMS THE COST-BENEFIT ANALYSIS REPORTED IN THE PAPER'S SECTION 7
*/

cd ${work}5_reg_analysis

*** AGGREGATE MARKUPS
use input\sample_ipt, clear
destring jurnr, gen(jurnr_num)

*MERGE ON OUTCOMES FROM DE LOECKER ET AL. PROCEDURE
merge 1:1 jurnr_num vnr unit year using input\vars_ipt, keep(3) keepusing(sales log_mu exit_x) nogen

*EXCLUDE SMALL FLOWS
keep if sales>7.5

*EXCLUDE OUTLIERS OF ESTIMATED MARKUPS (FOLLOWING DE LOECKER ET AL.)
keep if exit_x>0 | exit_x==.
drop exit_x
winsor2 log_mu, cuts(3 97) trim replace
keep if log_mu!=.

*COLLAPSE TO INDUSTRY
gen mu=exp(log_mu)
merge m:1 jurnr year using input\firm_it, assert(2 3) keep(3) keepusing(nace4) nogen
collapse (mean) mu [aw=sales] , by(nace4)

*SAVE
save temp\markups_nace4, replace




*** ANALYSIS
use jurnr land year vrd_exp_exsmall nace4 itemvalue_1 itemvalue_lag treated_2 using temp\regsample_idt, clear

*COST OF EXPORT SUPPORT
gen cost_1 = itemvalue_1 * 2.75
gen cost_lag = itemvalue_lag * 2.75
egen cost = rowmean(cost_1 cost_lag)
drop itemvalue_1 itemvalue_lag cost_1 cost_lag

* MERGE ON MARKUPS
merge m:1 nace4 using temp\markups_nace4, assert(1 3) keep(3) keepusing(mu) nogen
erase temp\markups_nace4.dta
drop nace4

* INTENSIVE MARGIN ONLY
keep if vrd_exp_exsmall>0

* VAR PROFITS
gen var_profits = (1-1/mu) * vrd_exp_exsmall
winsor2 var_profits, cuts(1 99) replace
drop vrd_exp_exsmall

* ANALYSIS BASED ON TREATED OBSERVATIONS ONLY
keep if treated_2==1
drop treated_2

* EFFECTS
local x=exp(0.0874)-1
disp "Effect of export support on export profits: `x'"

gen gain = var_profits * `x' / (1+`x')
gen ratio=gain/cost

*OUTPUT
qui {
log using output\costbenefit , text replace

*calculate pseudo median as mean of the five observations around the median to comply with DST's rules on data confidentiality
sort ratio
gen n=_n
sum n, det
local median=round(r(p50))
sum ratio if inrange(n,`median'-2,`median'+2)
noi disp "Median gain-cost ratio:"
noi disp r(mean)
drop n

count if ratio>1
local n=r(N)
count
noi disp "Share of observations where gain exceeds cost (%):"
noi disp `n'/r(N) *100

collapse (sum) gain cost
noi disp "Aggregate return to investment:"
noi disp gain / cost

log close

}